<template>
  <input v-if="isUploadInput" v-show="false" id="upload-input" type="file" @change="upload($event)" accept="image/png, image/gif, image/jpeg"/>
</template>

<script>
  import { uploadOssMixin } from '../mixins'

    export default {
      name: 'aUpload',
      mixins: [uploadOssMixin],
      props: {
      },
      data () {
        return {
          isUploadInput: true
        }
      },
      computed: {
      },
      watch: {
      },
      methods: {
        openFileDialog () {
          document.getElementById('upload-input').click()
        },
        async upload (event) {
          this.$emit('startLoading')
          let file = event.target.files[0],
            maxSize = this.maxSize

          this.isUploadInput = false

          setTimeout(() => {
            this.isUploadInput = true
          }, 100)

          if (maxSize && file.size > maxSize * 1024 * 1024) {
            this.notify('error', `上传图片不能超过${maxSize}MB`)
            this.$emit('stopLoading')
            return
          }

          const dataUrl = await this.readFile(file)
          const size = await this.getImageSize(dataUrl)
          const { status, data } = await this.uploadOssFile(file, 'forum', size)
          this.$emit('stopLoading')
          if (status === 200) {
            this.$emit('uploaded', data.url)
          } else {
            this.notify('error', '上传图片失败，请稍后重试！')
          }
        }
      }
    }
</script>

<style lang="stylus">
</style>
